package com.ruoyi.framework.encrypt;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.encrypt.utils.JsonUtil;
import com.ruoyi.framework.encrypt.wrapper.RequestBodyWrapper;
import com.ruoyi.framework.encrypt.wrapper.RequestParameterWrapper;
import com.zgl.youshuda.core.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import com.ruoyi.framework.encrypt.utils.RSAUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 请求参数解密过滤器
 **/
@Slf4j
public class ParamsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest) req;

        // 1. 排除不需要过滤的请求
        String authEncrypt = request.getHeader("Accept-Encrypt");
        if (!RuoYiConfig.isEncryReqParams() ||
                RuoYiConfig.isEncryReqParams() && request.getServletPath().startsWith("/MksAp/") && StringUtils.isEmptyIncludeNull(authEncrypt)) {
            chain.doFilter(req,resp); // 直接放行，不执行后续过滤逻辑
            return;
        }
        // 获取你需要的参数
        String dataInfo = request.getParameter("dataInfo");
        /**
         * 判断是否可以直接通过 getParameter 获取参数 一般 GET请求可以直接获取
         */
        if (StringUtils.isEmptyIncludeNull(dataInfo)) {
            /**
             * POST 请求进入这里
             */
            if ("POST,PUT,DELETE".indexOf(request.getMethod().toUpperCase()) > -1) {
                /**
                 * 获取post中的请求参数
                 */
                String postContent = getBody(request);
                /**
                 * POST请求存在加密参数
                 */
                if (StringUtils.isNotEmptyIncludeNull(postContent) && !"{}".equals(postContent)) {
                    //POST请求的全部参数
                    JSONObject jsStr = JSONObject.parseObject(postContent);
                    //加密的数据
                    dataInfo = jsStr.getString("dataInfo");
                    if (StringUtils.isNotEmptyIncludeNull(dataInfo)) {
                        try {
                            //密文
                            dataInfo = dataInfo.replaceAll("%2B", "\\+");
                            String dataStr = RSAUtils.decrypt(dataInfo);
                            //校验是否是json
                            boolean validate = JsonUtil.getInstance().validate(dataStr);
                            if (!validate) {
                                new RuntimeException("解密异常!");
                            }

                            if (dataStr.endsWith("]") && dataStr.startsWith("[")) {
                                //将参数放入重写的方法中
                                req = new RequestBodyWrapper(request, dataStr);
                            } else {
                                //将机密后的参数转为JSON对象
                                JSONObject dataJson = JSONObject.parseObject(dataStr);
                                //合并后面参数
                                dataJson.putAll(jsStr);
                                dataJson.forEach((key, value) -> {
                                    if (CommonUtil.stringIsNull(value)) {
                                        dataJson.put(key, null);
                                    }
                                });
                                //将参数放入重写的方法中
                                req = new RequestBodyWrapper(request, dataJson.toString());
                            }


                        } catch (Exception e) {
                            e.printStackTrace();
                            new RuntimeException("参数解密时错误，请联系管理员");
                        }
                    }
                } else {
                    req = new RequestBodyWrapper(request, "{}");
                }
                chain.doFilter(req, resp);
            } else {
                chain.doFilter(req, resp);
            }
        } else {
            try {
                //密文
                dataInfo = dataInfo.replaceAll("%2B", "\\+");
                String dataStr = RSAUtils.decrypt(dataInfo);
                //校验是否是json
                boolean validate = JsonUtil.getInstance().validate(dataStr);
                if (!validate) {
                    new RuntimeException("解密异常!");
                }
                //将所有的解密参数转为Map
                Map<String, Object> dataJson = JSONObject.parseObject(dataStr, HashMap.class);
                /**
                 * 处理json对象中，值为{}的情况
                 */
                for (Map.Entry<String, Object> item : dataJson.entrySet()) {
                    if ("{}".equals(String.valueOf(dataJson.get(item.getKey())))) {
                        dataJson.put(item.getKey(), null);
                    }
                }
                //将参数放入重写的request
                RequestParameterWrapper wrapper = new RequestParameterWrapper(request);
                //设置传输参数
                wrapper.addParameters(dataJson);
                //放行
                chain.doFilter(wrapper, resp);
            } catch (Exception e) {
                e.printStackTrace();
                new RuntimeException("参数解密时错误，请联系管理员");
            }
        }
    }


    /**
     * 获取Body中的数据
     *
     * @param request
     * @return
     */
    private String getBody(ServletRequest request) {
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        InputStream inputStream = null;
        try {
            inputStream = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            } else {
                stringBuilder.append("");
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return stringBuilder.toString();
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
//        Filter.super.init(filterConfig);
    }

    @Override
    public void destroy() {
//        Filter.super.destroy();
    }
}
